﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Way.Bus.WMS.Model;
using Way.Contract.Data;
using Way.Contract.MVC;
using Way.EAP.DataAccess.Entity;
using Way.Bus.WMS.Controllers;
using Way.Bus.Controllers;
using Way.EAP.DataAccess.Data;
using System.Data;
using Way.Bus.Model;
using Way.Contract.Data.ControllerData;
using Way.Bus.Wms.Model;
using Way.Contract;

namespace Way.Bus.WMS.ST.Controllers.InOrder
{
  public class ReceiveNoticeController : StockInNoticeController
    {
        public ReceiveNoticeController() : base(new StockInNotice()) { }

        #region 重写方法
        //是否启用审核
        public override bool IsReviewedState
        {
            get
            {
                return false;
            }
        }
        //显示在菜单
        protected override string OnControllerName()
        {
            return "预收单管理";
        }
        //说明
        protected override string OnGetControllerDescription()
        {
            return "预收单管理";
        }
        //菜单中url路径
        protected override string OnGetPath()
        {
            return "Views/ST/ReceiveNotice.htm";
        }
        
        //protected override void OnForeignLoading(Way.Contract.MVC.IModel model, Way.Contract.Data.ControllerData.loadItem item)
        //{
        //    //设置客户选择框只能选择客户类型的用户信息
        //    if (this.fdata.filedname == "CLIENTNO")
        //    {
        //        item.rowsql = "select * from (" + item.rowsql + ") t where t.ftype = '2'";
        //    }
        //    //设置销售人员选择框只能选择销售员类型的用户信息
        //    if (this.fdata.filedname == "WORKERID")
        //    {
        //        item.rowsql = "select t.* from (" + item.rowsql + ") t LEFT JOIN Acc_Bus_UserRole t1 on t.[ID]=t1.[UserID] WHERE t1.RoleID = '2'";
        //    }
        //}

        protected override ReadTable OnForeignLoad(IModel model, loadItem item)
        {
            //设置客户选择框只能选择客户类型的用户信息
            if (this.fdata.filedname == "CLIENTNO")
            {
                item.rowsql = "select * from (" + item.rowsql + ") t " + "where t.ftype = '2'";
            }
            //设置销售人员选择框只能选择销售员类型的用户信息
            if (this.fdata.filedname == "WORKERID")
            {
                item.rowsql = "select t.* from (" + item.rowsql + ") t LEFT JOIN Acc_Bus_UserRole t1 on t.[ID]=t1.[UserID] " + "WHERE t1.RoleID = '6'";
            }
            //根据客户名称选择商品
            if (this.fdata.filedname == "MATERIALCODE")
            {
                int kid = 0;
                if (this.ActionItem["CLIENTNO"] != null && !string.IsNullOrEmpty(this.ActionItem["CLIENTNO"].ToString()))
                    kid = int.Parse(this.ActionItem["CLIENTNO"].ToString());
                else
                    throw new Exception("异常：请先选择客户！");
                item.rowsql = "select t.* from (" + item.rowsql + ") t where STAY10 = '" + kid + "'";
            }
            return base.OnForeignLoad(model, item);
        }

        protected override void OnForeignLoaded(IModel model, ReadTable table)
        {
            base.OnForeignLoaded(model, table);
        }

        /// <summary>
        /// 初始化显示与否
        /// </summary>
        /// <param name="data"></param>
        /// <param name="item"></param>
        protected override void OnInitViewChildItem(ModelData data, ItemData item)
        {
            if (item.IsField("rowindex"))
            {
                item.isedit = false;
            }
            InitInNotice(data, item);
            InitInNoticeMaterials(data, item);
        }

        public static void InitInNotice(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("StockInNotice"))
            {
                //修改弹出窗口的title
                data.title = "预收单";
                //设置字段不能为空
                if (item.IsField("SourceOutCode"))
                {
                    item.required = true;
                }
                if (item.IsField("ISSQE"))
                    item.visible = true;
                //隐藏属性信息
                if (item.IsField("SourceCode")
                      || item.IsField("OfficeWorker")
                      || item.IsField("STOCKTYPE")
                      || item.IsField("IsDisable")
                      || item.IsField("SourceName")
                      || item.IsField("Reviewedby")
                      || item.IsField("Revieweddate")
                      || item.IsField("IsReviewed")
                      || item.IsField("RowIndex")
                      || item.IsField("WORKERID")
                      || item.IsField("BUMEN")
                    )
                    item.visible = false;
                if (item.IsField("CLIENTNO"))
                {
                    item.title = "客户";
                    item.required = true;
                }
                //设置不可写
                if (item.IsField("CODE"))
                {
                    item.title = "单号";
                    item.disabled = true;
                }
                //设置顺序
                if (item.field=="REMARK")
                    item.index = 4;
                if (item.field == "FINISHTIME")
                    item.index = 6;
                if (item.field == "ISSQE")
                    item.index = 999;
                if (item.IsField("STATE"))
                    item.disabled = true;

                //选择销售人员自动带出部门信息
                if (item.IsField("WORKERID"))
                {
                    if (item.foreign != null)
                    {
                        item.foreign.rowdisplay.Add(("OrganizationID").ToUpper(), "BUMEN");//key是联系人表字段，value是客户表字段
                    }
                }

            }
        }

        public static void InitInNoticeMaterials(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("StockInNoticeMaterials"))
            {
                data.title = "预收单明细";
                if (item.IsField("PARENTID")
                     || item.IsField("SourceCode")
                     || item.IsField("STATE")
                     || item.IsField("BATCHNO")
                     || item.IsField("BUMEN")
                     || item.IsField("WORKERID")
                     || item.IsField("IsDisable")
                     || item.IsField("code")
                     || item.IsField("Createdby")
                     || item.IsField("Creationdate")
                     || item.IsField("Reviewedby")
                     || item.IsField("Revieweddate")
                     || item.IsField("Submitedby")
                     || item.IsField("IsReviewed")
                     || item.IsField("IsSubmited")
                     || item.IsField("Submiteddate")
                     || item.IsField("DEPOTWBS")
                     || item.IsField("CODE")
                     || item.IsField("CLASSID")
                     || item.IsField("HQName"))
                    item.visible = false;
                if (item.IsField("MATERIALCODE"))
                {
                    item.title = "货物名称";
                    item.required = true;
                }
                if (item.IsField("MCODE"))
                    item.title = "货物编码";
                if (item.IsField("FINISHNUM")
                    || item.IsField("STAYNUM")
                    || item.IsField("FMODEL")
                    || item.IsField("MCODE"))
                    item.disabled = true;
                if (item.IsField("materialcode"))
                {
                    if (item.foreign != null)
                    {
                        //item.foreign.rowdisplay.Add("FMOBILE", "FMOBILE");//key是联系人表字段，value是客户表字段
                        item.foreign.rowdisplay.Add("FMODEL", "FMODEL");
                        item.foreign.rowdisplay.Add("CODE", "MCODE");
                        item.foreign.rowdisplay.Add("FUNITID", "FUNITID");//单位
                    }
                }

            }
        }

        public static void InitMaterials(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("Materials"))
            {
                data.title = "货物明细";
                if ( item.IsField("FFULLNAME")
                     || item.IsField("CLASSID")
                     || item.IsField("CUSTOMEAN13")
                     || item.IsField("FUNITID")
                     || item.IsField("COMMODITYTYPE")
                     || item.IsField("ISRESERVE")
                     || item.IsField("ISPERIOD")
                     || item.IsField("OUTWAREHOUSEYPE")
                     || item.IsField("CREATEDBY")
                     || item.IsField("CREATIONDATE")
                     || item.IsField("ISSUBMITED")
                     || item.IsField("SUBMITEDBY")
                     || item.IsField("SUBMITEDDATE")
                     || item.IsField("ISREVIEWED")
                     || item.IsField("REVIEWEDBY")
                     || item.IsField("REVIEWEDDATE")
                     || item.IsField("STOREAMOUNT")
                     || item.IsField("NUMSTATE")
                     || item.IsField("ISLESSIN")
                     || item.IsField("ISCHECKPRO")
                     || item.IsField("ISOVERIN")
                     || item.IsField("ISDISABLE")
                     || item.IsField("ISCHECKPRO")
                     || item.IsField("REMARK"))
                    item.visible = false;
                if (item.IsField("FNAME"))
                {
                    item.title = "货物名称";
                    item.required = true;
                }
                if (item.IsField("CODE"))
                    item.title = "货物编码";
                if (item.IsField("materialcode"))
                {
                    if (item.foreign != null)
                    {
                        //item.foreign.rowdisplay.Add("FMOBILE", "FMOBILE");//key是联系人表字段，value是客户表字段
                        item.foreign.rowdisplay.Add("FMODEL", "FMODEL");
                        item.foreign.rowdisplay.Add("CODE", "MCODE");
                        item.foreign.rowdisplay.Add("FUNITID", "FUNITID");//单位
                    }
                }

            }
        }

        protected override void OnAdding(ControllerBase.SaveEvent item)
        {
            //isBatchManagement(item);
            Merger(item);
            base.OnAdding(item);
        }

        protected override void OnEditing(ControllerBase.SaveEvent item)
        {
            //isBatchManagement(item);
            Merger( item);
            base.OnEditing(item);
        }

        protected override void OnRemoveing(ControllerBase.SaveEvent item)
        {
            isExistInOrder(item);
            base.OnRemoveing(item);
        }

        protected override void OnSubmitData(BasicInfo info)
        {
            StockInNotice sin = info as StockInNotice;
            sin.Materials.DataAction = this.model.GetDataAction();
            sin.Materials.GetData();
            if (sin.Materials.Count == 0)
            {
                throw new Exception("单据无明细数据不能提交！");
            }

            List<StockInNoticeMaterials> sonmList = new List<StockInNoticeMaterials>();
            for (int i = 0; i < sin.Materials.Count; i++)
            {
                sonmList.Add(sin.Materials[i]);
            }
            for (int i = 0; i < sonmList.Count; i++)
            {
                StockInNoticeMaterials temp = sonmList[i];
                bool resultbl = false;
                for (int l = 0; l < sin.Materials.Count; l++)
                {
                    if (sin.Materials[l].MATERIALCODE == temp.MATERIALCODE && resultbl == true)
                    {
                        EntityList<Materials> soo = new EntityList<Materials>(this.model.GetDataAction());
                        soo.GetData("ID='" + temp.MATERIALCODE + "'");
                        if (soo.Count > 0)
                            throw new Exception("明细产品 '" + soo[0].FNAME + "' 出现重复行，请手动合并！");
                    }
                    if (sin.Materials[l].MATERIALCODE == temp.MATERIALCODE && resultbl == false)
                        resultbl = true;
                }
            }

            try
            {
                base.OnSubmitData(info);
            }
            catch (Exception ex)
            {
                //base.OnUnSubmitData(info);
                throw ex;
            }
        }

        [ActionCommand(name = "导入", title = "导入", index = 6, icon = "icon-down", isselectrow = false, editshow=true, onclick = "import2")]
        public void ImportExcel()
        {

        }

        [ActionCommand(name = "导出", title = "导出", index = 10, icon = "icon-down", isselectrow = false, onclick = "emport2")]
        public void Emport()
        {
            //ExcelDRController er = new ExcelDRController();
            //er.bc = this;
        }

        //判断是否存在预收单明细
        public BasicInfo info { get; set; }
        public void isExistInNoticeMaterials()
        {
            if (info != null)
            {
                StockInNotice sin = info as StockInNotice;
                sin.Materials.DataAction = this.model.GetDataAction();
                sin.Materials.GetData();
                if (sin.Materials.Count == 0)
                {
                    throw new Exception("操作失败，该预收单中已包含明细数据！请在删除明细数据后，再对该预收单进行操作。");
                }
            }
        }
        
        protected override void OnUnSubmitData(Bus.Model.BasicInfo info)
        {
            isSubmitedStatus(info);
            base.OnUnSubmitData(info);
        }

        //判断预收单对应的入库单是否存在，若存在则提醒客户不允许操作
        public void isExistInOrder(ControllerBase.SaveEvent item)
        {
            StockInNotice son = item.Item as StockInNotice;
            EntityList<StockInOrder> soo = new EntityList<StockInOrder>(this.model.GetDataAction());
            soo.GetData("SourceID='" + son.ID + "'");
            if (soo.Count != 0)
            {
                throw new Exception("操作失败，该预收单存在对应的入库单！请在删除入库单后，再对该预收单进行操作。");
            }
        }

        //判断预收单中待入库的商品是否需要批次管理，如果需要批次管理，则提醒用户必须录入批次号
        public void isBatchManagement(ControllerBase.SaveEvent item)
        {
            StockInNotice son = item.Item as StockInNotice;
            for (int i = 0; i < son.Materials.Count; i++)
            {
                var mcode = son.Materials[i].MCODE;
                var batchno = son.Materials[i].BATCHNO;
                EntityList<Materials> soo = new EntityList<Materials>(this.model.GetDataAction());
                soo.GetData("code='" + mcode + "'");
                if (soo.Count != 0)
                {
                    if (soo[0].BATCH == true && (batchno == null || batchno==""))
                    {
                        throw new Exception("该商品的批次号不能为空。");
                    }
                }
            }
        }

        //获得入库单的提交状态，如果已提交，则提示“预收单不能撤销提交”
        public void isSubmitedStatus(Bus.Model.BasicInfo info)
        {
            IDataAction action = this.model.GetDataAction();
            string sqlSelect = "select IsSubmited from Acc_WMS_InOrder " +
                               "where SourceID = '" + info.ID + "' ";
            DataTable oldDataTable = action.GetDataTable(sqlSelect);
            foreach (DataRow oldRow in oldDataTable.Rows)
            {
                if (Convert.ToBoolean(oldRow["IsSubmited"]))
                {
                    throw new Exception("异常：入库单已提交，因此预收单不能撤销提交！");
                }else
                {
                    throw new Exception("异常：入库单已存在，如需撤销预收单，请先删除对应的入库单信息！");
                }
            }

        }

        //对象排序
        public int SortByMcode(StockInNoticeMaterials x, StockInNoticeMaterials y)
        {
            return (x.MCODE.CompareTo(y.MCODE));
        }

        //virtual

        /// <summary>
        /// 单据转换
        /// </summary>
        /// <returns></returns>
        protected override ControllerAssociate[] DownAssociate()
        {
            List<ControllerAssociate> list = new List<ControllerAssociate>();
            //入库通知下推入库单
            RelationOrder(list);
            return list.ToArray();
        }

        /// <summary>
        /// 入库通知-入库单(下推关联)
        /// </summary>
        /// <param name="list"></param>
        public virtual void RelationOrder(List<ControllerAssociate> list)
        {
            //控制器转换器入库通知-入库单

            ControllerAssociate b2 = new ControllerAssociate(this, new ReceiveOrderController());

            //单据属性映射
            PropertyMap map1 = new PropertyMap();
            ///预收单CODE--入库单原单编码SourceCode
            map1.TargerProperty = "SourceCode";
            map1.SourceProperty = "CODE";
            b2.Convert.AddPropertyMap(map1);

            //PropertyMap map2 = new PropertyMap();//ID
            //map2.TargerProperty = "STATE";
            //map2.IsValue = true;
            //map2.Value = "3";
            //b2.Convert.AddPropertyMap(map2);

            PropertyMap map3 = new PropertyMap();//ID
            map3.TargerProperty = "CODE";
            map3.IsValue = true;
            map3.Value = "";
            b2.Convert.AddPropertyMap(map3);

            //实体类型转换器（入库通知单-入库单）
            //此处注释掉，不下推入库单明细
            //ConvertAssociate nTo = new ConvertAssociate();
            //nTo.SourceType = typeof(StockInNoticeMaterials);//下推来源单据子集
            //nTo.TargerType = typeof(StockInOrderMaterials);//下推目标单据子集
            //YS(nTo);
            //b2.AddConvert(nTo);
            list.Add(b2);
        }

        /// <summary>
        /// 映射
        /// </summary>
        /// <param name="c"></param>
        public virtual void YS(ConvertAssociate c)
        {
            PropertyMap mapMATERIALSID = new PropertyMap();//ID
            mapMATERIALSID.SourceProperty = "CODE";
            mapMATERIALSID.TargerProperty = "SourceCode";
            c.AddPropertyMap(mapMATERIALSID);

            PropertyMap map11 = new PropertyMap();//ID
            map11.SourceProperty = "p.ID";
            map11.TargerProperty = "SourceID";

            PropertyMap map12 = new PropertyMap();//ID
            map12.TargerProperty = "SourceController";
            map12.IsValue = true;
            map12.Value = this.ToString();

            PropertyMap map13 = new PropertyMap();//ID
            map13.SourceProperty = "ID";
            map13.TargerProperty = "SourceRowID";

            PropertyMap map14 = new PropertyMap();//ID
            map14.SourceProperty = "p.Code";
            map14.TargerProperty = "SourceCode";

            PropertyMap map15 = new PropertyMap();//ID
            map15.TargerProperty = "SourceName";
            map15.IsValue = true;
            map15.Value = ((IController)this).ControllerName();

            PropertyMap map16 = new PropertyMap();//ID
            map16.TargerProperty = "SourceTable";
            map16.IsValue = true;
            map16.Value = new StockInNoticeMaterials().ToString();

            //PropertyMap map17 = new PropertyMap();//ID
            //map17.SourceProperty = "STAYNUM";
            //map17.TargerProperty = "STAYNUM";


            //PropertyMap map18 = new PropertyMap();//ID
            //map18.SourceProperty = "FINISHNUM";
            //map18.TargerProperty = "FINISHNUM";

            c.AddPropertyMap(map11);
            c.AddPropertyMap(map12);
            c.AddPropertyMap(map13);
            c.AddPropertyMap(map14);
            c.AddPropertyMap(map15);
            c.AddPropertyMap(map16);
            //c.AddPropertyMap(map17);
            //c.AddPropertyMap(map18);
        }

        /// <summary>
        /// 单据转换
        /// </summary>
        /// <param name="ca"></param>
        /// <param name="actionItem"></param>
        /// <returns></returns>
        protected override EntityBase OnConvertItem(ControllerAssociate ca, EntityBase actionItem)
        {
            //下推前判断
            WMShelp.IsPush(this);
            StockInNotice cd = actionItem as StockInNotice;
            cd.Materials.DataAction = this.model.GetDataAction();
            cd.Materials.GetData();//获取子集的数据
            bool isconvert = false;
            foreach (StockInNoticeMaterials sonm in cd.Materials)
            {
                if (sonm.STAYNUM > 0)
                {
                    isconvert = true;
                }
            }
            if (!isconvert)
                throw new Exception("异常：预收单已全部操作完毕不能下推！");
            EntityBase eb = base.OnConvertItem(ca, actionItem);
            if (ca.cData.name.EndsWith("ReceiveOrderController"))
                eb = PushInOrder(eb, cd);//下推
            eb["Remark"] = actionItem["Remark"];
            return eb;
        }

        /// <summary>
        /// 下推判断
        /// </summary>
        /// <param name="eb"></param>
        /// <param name="cd"></param>
        /// <returns></returns>
        protected virtual EntityBase PushInOrder(EntityBase eb, StockInNotice cd)
        {
            if (eb is StockInOrder)
            {
                StockInOrder ebin = eb as StockInOrder;
                string sourceCode = eb.GetAppendPropertyKey("SOURCECODE");
                ebin[sourceCode] = ebin.GetForeignObject<StockInNotice>(this.model.GetDataAction()).Code;
                //string clientNo = eb.GetAppendPropertyKey("CLIENTNO");
                //ebin[clientNo] = ebin.GetForeignObject<StockInNotice>(this.model.GetDataAction()).CLIENTNO;
                string cname = eb.GetAppendPropertyKey("CLIENTNO");
                string ccname = cd.GetAppendPropertyKey("CLIENTNO");
                ebin.CLIENTNO = cd.CLIENTNO;
                ebin[cname] = cd[ccname];
                ebin.STATE = 0;
                ebin.STOCKTYPE = SetStockType();
                if (cd.FINISHTIME.ToString() == "1900/1/1 0:00:00") //如果完成时间为MinValue，则取当前时间
                    ebin.FINISHTIME = DateTime.Now;
                ebin.IsSubmited = false;
                ebin.IsReviewed = false;
                ebin.SourceID = cd.ID;
                ebin.SourceController = this.ToString();
                //ebin.Code = new BillNumberController().GetBillNo(bc());
                ebin[ebin.GetAppendPropertyKey("Createdby")] = "";
                ebin[ebin.GetAppendPropertyKey("Submitedby")] = "";
                ebin.Submiteddate = DateTime.MinValue;
                ebin.Creationdate = DateTime.MinValue;
                ebin.Reviewedby = "";
                ebin.Revieweddate = DateTime.MinValue;
                ebin.Modifiedby = "";
                ebin.Modifieddate = DateTime.MinValue;
                ebin.StayMaterials.DataAction = this.model.GetDataAction();
                int id = ebin.GetForeignObject<StockInNotice>(this.model.GetDataAction()).ID;
                ebin.StayMaterials.GetData("ParentId=" + id + "");

                //旧版本：直接取所有可用货位，为每个明细行分配一个货位。---------于12月01日注释掉
                //改成在ReceiveOrderController的OnAdding方法中处理。
                //IDataAction ida = this.model.GetDataAction();
                //DataTable dt = ida.GetDataTable("select CODE from Acc_WMS_WareHouse where WHTYPE = '2' and STATUS = '0'");
                //int inNoticeCount = 0;  //预收单明细记录数
                //int wbsCount = dt.Rows.Count - 1;  //推荐货位个数
                //foreach (StockInNoticeMaterials sinm in ebin.StayMaterials)
                //{
                //    if (wbsCount >= inNoticeCount)
                //    {
                //        sinm.DEPOTWBS = dt.Rows[inNoticeCount][0].ToString();

                //    }
                //    else if (dt.Rows.Count > 0)
                //    {
                //        sinm.DEPOTWBS = dt.Rows[wbsCount][0].ToString();
                //    }
                //    inNoticeCount++;
                //}

                eb = ebin;

            }
            return eb;
        }

        public virtual BusinessController bc()
        {
            return new BusinessController();
        }

        /// <summary>
        /// 添加不同类型
        /// </summary>
        /// <param name="item"></param>
        /// <param name="stockType"></param>
        public virtual int SetStockType()
        {
            return 0;
        }

        
        #endregion


    }
}
